package com.firewolf.oa.action;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;

import com.firewolf.oa.entities.Permission;
import com.firewolf.oa.service.PermissionService;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 初始化Action
 * 
 * @author liuxing
 *
 */
@Controller
@Scope("prototype")
public class InitAction extends ActionSupport {

	private static final long serialVersionUID = 6832741542523355506L;

	@Autowired
	private PermissionService permissionService;

	/**
	 * 初始化所有数据
	 * 
	 * @return
	 */
	public String all() {
		try {
			initPermission();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "success";
	}

	/**
	 * 初始化权限
	 */
	private void initPermission() throws Exception {

		//数据库中已经存在的权限列表
		List<Permission> oldPlist = permissionService.findAll();
		Map<String, Permission> oldMap = new HashMap<>();
		for(Permission p : oldPlist){
			oldMap.put(p.getCode(), p);
		}
		
		// 从文件中读取数据
		FileReader fr = null;
		BufferedReader br = null;
		try {
			fr = new FileReader("menu.txt");
			br = new BufferedReader(fr);
			String permissionStr = null;
			while ((permissionStr = br.readLine()) != null) {
				if (!StringUtils.isEmpty(permissionStr) && !permissionStr.startsWith("#")) {
					
					//构建一个新的权限
					Permission p = new Permission();
					String[] split = permissionStr.split(",");
					p.setCode(split[0]);
					p.setName(split[1]);
					if (split.length > 2)
						p.setUrl(split[2]);
					if (split.length > 3) {
						Permission parent = oldMap.get(split[3]);
						if (parent != null)
							p.setParent(parent);
					}
					//判断，旧的是否存在，存在的话，就修改
					Permission permission = oldMap.get(p.getCode());
					if(permission != null && !permission.equals(p)){//证明已经存在，判断两个是否相同，如果相同，就不管，否则更新
						permission.setCode(p.getCode());
						permission.setName(p.getName());
						permission.setParent(p.getParent());
						permission.setUrl(p.getUrl());
						permissionService.update(permission);//更新
					}else{
						permissionService.save(p);//保存
						oldMap.put(split[0], p);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fr != null)
					fr.close();
				if (br != null)
					br.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		try {
			new InitAction().initPermission();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();	
		}
	}
}
